package persistencia;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;

/**
 *
 * @author Juan Leal
 */
abstract class AbstractFacade<T> {

    private EntityManager em;
    private Class<T> entityClass;

    public AbstractFacade(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    public EntityManager getEntityManager() {
        if (this.em == null) {
            this.em = Persistence.createEntityManagerFactory("ProyectoFinal_Taxi-ejbPU").createEntityManager();
        }
        return this.em;
    }

    public boolean agregar(T entity) {
        getEntityManager().persist(entity);
        return true;
    }

    public boolean editar(T entity) {
        getEntityManager().merge(entity);
        return true;
    }

    public boolean eliminar(T entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
        return true;
    }

    public T buscar(Object id) {
        return getEntityManager().find(entityClass, id);
    }

    public List<T> listarTodos() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return getEntityManager().createQuery(cq).getResultList();
    }

    public int contar() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
        cq.select(getEntityManager().getCriteriaBuilder().count(rt));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }
}
